package com.tin.triper.Helper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.widget.Toast;

import com.tin.triper.Constants;
import com.tin.triper.R;
import com.tin.triper.Data.LocationProvider;
import com.tin.triper.Data.Resources;
import com.tin.triper.Data.Trip;
import com.tin.triper.Data.TripPoint;

public class Exporting {
	private static final String classResource = "resource";
	private static final String classDescription = "description";
	private static final String classMenu = "menu";

	private static final String markerBody = "#all#";
	private static final String markerTripStart = "#trip_start#";
	private static final String markerTripEnd = "#trip_end#";
	private static final String markerTripName = "#trip_name#";
	private static final String markerTripDistance = "#trip_distance#";
	private static final String markerTripTime = "#trip_time#";
	private static final String markerTripAvgSpeed = "#trip_avg_speed#";
	private static final String markerImageLink = "#image_link#";
	private static final String markerVideoLink = "#video_link#";
	private static final String markerVoiceLink = "#voice_link#";
	private static final String markerDescription = "#description#";
	private static final String markerPointDistance = "#point_distance#";
	private static final String markerPointTime = "#point_time#";
	private static final String marketResourceType = "#type#";
	private static final String markerPointAvgSpeed = "#point_avg_speed#";
	private static final String markerClassName = "#class_name#";
	private static final String markerName = "#name#";
	private static final String markerMenuLineText = "#text#";

	private static String htmlMenuLine = "<li><a href=\"##name#\">#text#</a> </li>";
	private static String htmlHead = "<head>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />\n</head>";
	private static String htmlDivOpen = "<div class=\"#class_name#\">\n";
	private static String htmlContentDiv = "<div align=\"center\" class=\"content\">\n";
	private static String htmlDivClose = "</div>\n";
	private static String htmlBody = "<html>" + htmlHead
			+ "\n<body>\n#all#</body>\n</html>\n";
	private static String htmlStatsTable = "<div class=\"stats\">\n<h3>Statistics</h3>\n<table>\n<tr>\n <td>Trip start</td>\n<td>#trip_start#</td>\n</tr>\n<tr>\n<td>Trip end</td>\n<td>#trip_end#</td>\n</tr>\n<tr>\n<td>Distance</td>\n<td>#trip_distance#</td>\n</tr>\n<tr>\n<td>Time</td>\n<td>#trip_time#</td>\n</tr>\n<tr>\n<td>Avg Speed</td>\n<td>#trip_avg_speed#</td>\n</tr>\n</table>\n</div>\n";
	private static String htmlImage = "<img src=\"#image_link#\" width=\"480\" height=\"640\" alt=\"\"class=\"media\"/>\n";
	private static String htmlVideo = "<embed type='application/x-mplayer2'\nwidth=\"480\" height=\"640\" class=\"media\" pluginspage='http://microsoft.com/windows/mediaplayer/en/download/'\nid='mediaPlayer' name='mediaPlayer' displaysize='4' autosize='-1'\nbgcolor='darkblue' showcontrols=\"true\" showtracker='-1'\nshowdisplay='0' showstatusbar='-1' videoborder3d='-1'\nsrc=\"#video_link#\" autostart=\"false\" designtimesp='5311' loop=\"false\"></embed>\n";
	private static String htmlVoice = "<embed type='application/x-mplayer2'\nwidth=\"640\" height=\"200\" class=\"media\" pluginspage='http://microsoft.com/windows/mediaplayer/en/download/'\nid='mediaPlayer' name='mediaPlayer' displaysize='4' autosize='-1'\nbgcolor='darkblue' showcontrols=\"true\" showtracker='-1'\nshowdisplay='0' showstatusbar='-1' videoborder3d='-1'\nsrc=\"#voice_link#\" autostart=\"false\" designtimesp='5311' loop=\"false\"></embed>\n";
	private static String htmlDescrption = "<div class=\"description\">\n<h3>Description</h3>\n<p>#description#</p>\n</div>\n";
	private static String htmlTextDescrption = "<p>#description#</p>\n";
	private static String htmlType = "<h3><a name=\"#name#\">#type#</a></h3>\n";
	private static String htmlName = "<h1>#trip_name#</h1>\n<p><a name=\"top\">This is trip generated with Triper</a></p>\n";
	private static String htmlPointDescription = "<img src=\"#image_link#\" alt=\"\"/ class=\"map\"> \n<div class=\"stats\">\n<h3>Statistics</h3><table>\n  <td>Distance</td> <td>#point_distance#</td>\n</tr>\n<tr>  \n<td>Time</td>  \n<td>#point_time#</td>\n</tr>\n<tr>\n  <td>Avg Speed</td>\n <td>#point_avg_speed#</td>\n</tr>\n</table>\n</div>\n";
	private static String htmlLine = "<hr />";

	public static void exportTripHtml(int tripId, Context context) {
		Trip trip = null;
		File tripFilePath = null;
		List<TripPoint> pointList = new ArrayList<TripPoint>();
		List<Resources> resourcesList = new ArrayList<Resources>();
		List<MenuItem> menuItemList = new ArrayList<MenuItem>();
		Cursor cursor = context.getContentResolver().query(
				LocationProvider.CONTENT_URI_TRIPS,
				new String[] { LocationProvider.TRIP_ID,
						LocationProvider.TRIP_NAME,
						LocationProvider.TRIP_LENGTH,
						LocationProvider.TRIP_TIME },
				LocationProvider.TRIP_ID + " ='" + tripId + "'", null, null);
		if (cursor != null)
			if (cursor.moveToFirst()) {
				trip = new Trip();
				trip.tripId = cursor.getInt(0);
				trip.tripName = cursor.getString(1);
				trip.tripTime = Formating.converseToTime(cursor.getInt(3),
						context);
				trip.tripLength = cursor.getFloat(2) / 1000 + "";
				tripFilePath = new File(Environment
						.getExternalStorageDirectory().getAbsolutePath()
						+ "/"
						+ Constants.APP_FOLDER_NAME
						+ "/"
						+ trip.tripId
						+ " "
						+ trip.tripName + "/");
				tripFilePath.mkdirs();
			}
		cursor.close();
		Cursor resourcesCursor = context.getContentResolver().query(
				LocationProvider.CONTENT_URI_RESOURCES,
				new String[] { LocationProvider.RESOURCE_ID,
						LocationProvider.LOCATION_ID,
						LocationProvider.RESOURCE_FILENAME,
						LocationProvider.RESOURCE_TYPE,
						LocationProvider.RESOURCE_DESCRIPTION },
				LocationProvider.TRIP_ID + " ='" + tripId + "'", null, null);
		if (resourcesCursor != null)
			while (resourcesCursor.moveToNext()) {
				Resources res = new Resources();
				res.id = resourcesCursor.getInt(0);
				res.locationId = resourcesCursor.getInt(1);
				res.fileName = resourcesCursor.getString(2);
				res.type = resourcesCursor.getInt(3);
				res.description = resourcesCursor.getString(4);
				resourcesList.add(res);
			}
		resourcesCursor.close();
		cursor = context.getContentResolver().query(
				LocationProvider.CONTENT_URI_LOCATION,
				new String[] { LocationProvider.LOCATION_LATITUDE,
						LocationProvider.LOCATION_LONGITUDE,
						LocationProvider.LOCATION_TIME,
						LocationProvider.LOCATION_ID },
				LocationProvider.TRIP_ID + " ='" + tripId + "'", null,
				LocationProvider.LOCATION_TIME);
		if (cursor != null)
			while (cursor.moveToNext()) {
				TripPoint point = new TripPoint(
						(int) (cursor.getDouble(0) * 1E6),
						(int) (cursor.getDouble(1) * 1E6), cursor.getLong(2),
						cursor.getInt(3));
				pointList.add(point);
			}
		cursor.close();
		for (int i = 0; i < resourcesList.size(); i++)
			for (int l = 0; l < pointList.size(); l++) {
				if (resourcesList.get(i).locationId == pointList.get(l).id)
					pointList.get(l).gotResouce = true;
			}
		int lastResourcePoint = 0;
		int currentResourcePoint = 0;
		InputStream googleMap = null;
		boolean exporting = true;
		String htmlPage = "";
		htmlPage += getFirstPage(pointList, trip, resourcesList, context,
				menuItemList);
		while (true) {
			for (int i = lastResourcePoint; i < pointList.size(); i++) {
				if (i == pointList.size() - 1)
					exporting = false;
				if (pointList.get(i).gotResouce) {
					currentResourcePoint = i;
					pointList.get(i).gotResouce = false;
					break;
				}

			}
			if (!exporting)
				break;
			htmlPage += htmlLine;
			try {

				googleMap = downloadGoogleMap(lastResourcePoint,
						currentResourcePoint, pointList, resourcesList,
						context, false);
				String googleMapName = "Map " + lastResourcePoint + " "
						+ currentResourcePoint + ".gif";
				File googleMapFilePath = new File(Environment
						.getExternalStorageDirectory().getAbsolutePath()
						+ "/"
						+ Constants.APP_FOLDER_NAME
						+ "/"
						+ trip.tripId
						+ " "
						+ trip.tripName + "/Map Images/");
				googleMapFilePath.mkdirs();
				File googleMapFile = new File(googleMapFilePath, googleMapName);
				FileOutputStream fOut = new FileOutputStream(googleMapFile);
				byte[] buffer = new byte[2048];
				int length;
				try {
					while ((length = googleMap.read(buffer)) > 0) {
						fOut.write(buffer, 0, length);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				String newHtmlPointDescription = htmlPointDescription;
				newHtmlPointDescription = newHtmlPointDescription.replace(
						markerImageLink, "Map Images/" + googleMapName);
				newHtmlPointDescription = newHtmlPointDescription.replace(
						markerPointDistance,
						getDistance(lastResourcePoint, currentResourcePoint,
								pointList) + " km");
				newHtmlPointDescription = newHtmlPointDescription.replace(
						markerPointTime, Formating.converseToTime(
								getTime(lastResourcePoint,
										currentResourcePoint, pointList),
								context));
				newHtmlPointDescription = newHtmlPointDescription.replace(
						markerPointAvgSpeed,
						getAvgSpeed(lastResourcePoint, currentResourcePoint,
								pointList) + " km/h");
				htmlPage += getResource(currentResourcePoint, pointList,
						resourcesList, context, newHtmlPointDescription,
						menuItemList);
			} catch (Exception e) {
				e.printStackTrace();
			}

			lastResourcePoint = currentResourcePoint;
		}
		htmlPage += getMenu(menuItemList, context);
		String newHtmlBody = htmlBody;
		newHtmlBody = newHtmlBody.replace(markerBody, htmlPage);
		try {
			File tripFile = new File(tripFilePath, "trip.html");
			FileOutputStream fOut = new FileOutputStream(tripFile);
			OutputStreamWriter osw = new OutputStreamWriter(fOut);
			osw.write(newHtmlBody);
			osw.flush();
			osw.close();
			InputStream inputStream = context.getResources().openRawResource(
					R.raw.style);
			File cssFile = new File(tripFilePath, "style.css");
			fOut = new FileOutputStream(cssFile);
			byte[] buffer = new byte[1024];
			int length;
			try {
				while ((length = inputStream.read(buffer)) > 0) {
					fOut.write(buffer, 0, length);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static String getMenu(List<MenuItem> menuItemList, Context context) {
		String newHtmlMenu = "";
		newHtmlMenu += htmlDivOpen.replace(markerClassName, classMenu);
		for (int i = 0; i < menuItemList.size(); i++) {
			newHtmlMenu += htmlMenuLine.replace(markerName,
					menuItemList.get(i).id).replace(markerMenuLineText,
					menuItemList.get(i).text);
		}
		newHtmlMenu += htmlDivClose;
		return newHtmlMenu;
	}

	private static String getFirstPage(List<TripPoint> pointList, Trip trip,
			List<Resources> resourcesList, Context context,
			List<MenuItem> menuItemList) {
		menuItemList.add(new MenuItem("top", context
				.getString(R.string.html_menu_top)));
		String newTripName = htmlName;
		String newHtmlImage = htmlImage;
		newTripName = newTripName.replace(markerTripName, trip.tripName);
		String newHtmlStatsTable = htmlStatsTable;
		newHtmlStatsTable = newHtmlStatsTable.replace(markerTripStart,
				getDate(0, pointList));
		newHtmlStatsTable = newHtmlStatsTable.replace(markerTripEnd,
				getDate(pointList.size() - 1, pointList));
		newHtmlStatsTable = newHtmlStatsTable.replace(markerTripDistance,
				trip.tripLength);
		newHtmlStatsTable = newHtmlStatsTable.replace(markerTripTime,
				trip.tripTime);
		newHtmlStatsTable = newHtmlStatsTable.replace(markerTripAvgSpeed,
				getAvgSpeed(0, pointList.size() - 1, pointList) + " km/h");
		try {
			InputStream googleMap = downloadGoogleMap(0, pointList.size() - 1,
					pointList, resourcesList, context, true);
			String googleMapName = "Map all.gif";
			File googleMapFilePath = new File(Environment
					.getExternalStorageDirectory().getAbsolutePath()
					+ "/"
					+ Constants.APP_FOLDER_NAME
					+ "/"
					+ trip.tripId
					+ " "
					+ trip.tripName + "/Map Images/");
			googleMapFilePath.mkdirs();
			File googleMapFile = new File(googleMapFilePath, googleMapName);
			FileOutputStream fOut = new FileOutputStream(googleMapFile);
			byte[] buffer = new byte[2048];
			int length;

			while ((length = googleMap.read(buffer)) > 0) {
				fOut.write(buffer, 0, length);
			}
			newHtmlImage = newHtmlImage.replace(markerImageLink, "Map Images/"
					+ googleMapName);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return htmlContentDiv + newTripName + newHtmlImage + newHtmlStatsTable
				+ htmlDivClose;
	}

	private static String getDate(int i, List<TripPoint> pointList) {
		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat(
				"yyyy.MM.dd 'at' H:mm:ss ");
		date.setTime(pointList.get(i).time);
		return formatter.format(date);
	}

	private static String getResource(int currentResourcePoint,
			List<TripPoint> pointList, List<Resources> resourcesList,
			Context context, String newHtmlPointDescription,
			List<MenuItem> menuList) {
		String newHtmlType = htmlType;
		String newHtmlDescription = htmlDescrption;
		for (int i = 0; i < resourcesList.size(); i++)
			if (pointList.get(currentResourcePoint).id == resourcesList.get(i).locationId) {
				newHtmlDescription = newHtmlDescription.replace(
						markerDescription, resourcesList.get(i).description);
				String text = resourcesList.get(i).description;
				if (text.length() > 10)
					text = text.substring(0, 10) + "...";
				else
					text = text.substring(0, text.length());
				switch (resourcesList.get(i).type) {
				case 0:
					newHtmlDescription = htmlTextDescrption
							.replace(markerDescription,
									resourcesList.get(i).description);
					newHtmlType = newHtmlType.replace(marketResourceType,
							context.getString(R.string.common_text));
					menuList.add(new MenuItem(context.getString(
							R.string.common_text).toLowerCase()
							+ currentResourcePoint, text));
					return htmlContentDiv
							+ newHtmlType.replace(markerName, context
									.getString(R.string.common_text)
									.toLowerCase()
									+ currentResourcePoint)
							+ newHtmlDescription + newHtmlPointDescription
							+ htmlDivClose;
				case 1:
					newHtmlType = newHtmlType.replace(marketResourceType,
							context.getString(R.string.common_voice));
					String newHtmlVoice = htmlVoice;
					newHtmlVoice = newHtmlVoice.replace(markerVoiceLink,
							"Voice/" + resourcesList.get(i).fileName);
					menuList.add(new MenuItem(context.getString(
							R.string.common_voice).toLowerCase()
							+ currentResourcePoint, text));
					return htmlContentDiv
							+ newHtmlType.replace(markerName, context
									.getString(R.string.common_voice)
									.toLowerCase()
									+ currentResourcePoint)
							+ newHtmlPointDescription
							+ htmlDivOpen.replace(markerClassName,
									classResource)
							+ newHtmlVoice
							+ htmlDivOpen.replace(markerClassName,
									classDescription) + newHtmlDescription
							+ htmlDivClose + htmlDivClose + htmlDivClose;
				case 2:
					newHtmlType = newHtmlType.replace(marketResourceType,
							context.getString(R.string.common_photo));
					String newHtmlImage = htmlImage;
					newHtmlImage = newHtmlImage.replace(markerImageLink,
							"Image/" + resourcesList.get(i).fileName);
					menuList.add(new MenuItem(context.getString(
							R.string.common_photo).toLowerCase()
							+ currentResourcePoint, text));
					return htmlContentDiv
							+ newHtmlType.replace(markerName, context
									.getString(R.string.common_photo)
									.toLowerCase()
									+ currentResourcePoint)
							+ newHtmlPointDescription
							+ htmlDivOpen.replace(markerClassName,
									classResource)
							+ newHtmlImage
							+ htmlDivOpen.replace(markerClassName,
									classDescription) + newHtmlDescription
							+ htmlDivClose + htmlDivClose + htmlDivClose;
				case 3:
					newHtmlType = newHtmlType.replace(marketResourceType,
							context.getString(R.string.common_video));
					String newHtmlVideo = htmlVideo;
					newHtmlVideo = newHtmlVideo.replace(markerVideoLink,
							"Video/" + resourcesList.get(i).fileName);
					menuList.add(new MenuItem(context.getString(
							R.string.common_video).toLowerCase()
							+ currentResourcePoint, text));
					return htmlContentDiv
							+ newHtmlType.replace(markerName, context
									.getString(R.string.common_video)
									.toLowerCase()
									+ currentResourcePoint)
							+ newHtmlPointDescription
							+ htmlDivOpen.replace(markerClassName,
									classResource)
							+ newHtmlVideo
							+ htmlDivOpen.replace(markerClassName,
									classDescription) + newHtmlDescription
							+ htmlDivClose + htmlDivClose + htmlDivClose;
				default:
					return "";
				}
			}
		return "";
	}

	private static InputStream downloadGoogleMap(int lastResourcePoint,
			int currentResourcePoint, List<TripPoint> pointList,
			List<Resources> resourcesList, Context context, boolean allMap)
			throws MalformedURLException, IOException {
		if (lastResourcePoint == currentResourcePoint) {
			if (lastResourcePoint - 2 >= 0)
				lastResourcePoint -= 2;
			else if (lastResourcePoint - 1 >= 0) {
				lastResourcePoint -= 1;
			}
		}
		String URL = "http://maps.googleapis.com/maps/api/staticmap?size=640x640&path=color:0x0000ff|weight:5";
		for (int i = lastResourcePoint; i <= currentResourcePoint; i++) {
			String point = "|";
			point += pointList.get(i).getLatitudeE6() / 1E6;
			point += ",";
			point += pointList.get(i).getLongitudeE6() / 1E6;
			URL += point;
		}
		if (!allMap) {
			String iconUrl = getResourceLabel(currentResourcePoint,
					resourcesList, pointList, context);
			URL += "&markers=icon:" + iconUrl + "%7C"
					+ pointList.get(currentResourcePoint).getLatitudeE6() / 1E6
					+ ","
					+ pointList.get(currentResourcePoint).getLongitudeE6()
					/ 1E6;
		}
		return getBitmapFromURL(URL + "&sensor=true");
	}

	private static String getResourceLabel(int currentResourcePoint,
			List<Resources> resourcesList, List<TripPoint> pointList,
			Context context) {
		for (int i = 0; i < resourcesList.size(); i++) {
			if (pointList.get(currentResourcePoint).id == resourcesList.get(i).locationId) {
				switch (resourcesList.get(i).type) {
				case 0:
					return context.getString(R.string.marker_text);
				case 1:
					return context.getString(R.string.marker_voice);
				case 2:
					return context.getString(R.string.marker_image);
				case 3:
					return context.getString(R.string.marker_video);
				default:
					break;
				}
			}
		}
		return "";
	}

	private static float getDistance(int lastResourcePoint,
			int currentResourcePoint, List<TripPoint> pointList) {
		float distance = 0;
		for (int i = lastResourcePoint + 1; i < currentResourcePoint; i++) {
			Location loc1 = new Location("none");
			Location loc2 = new Location("none");
			loc1.setLongitude(pointList.get(i - 1).getLongitudeE6() / 1e6);
			loc1.setLatitude(pointList.get(i - 1).getLatitudeE6() / 1e6);
			loc2.setLongitude(pointList.get(i).getLongitudeE6() / 1e6);
			loc2.setLatitude(pointList.get(i).getLatitudeE6() / 1e6);
			distance += loc1.distanceTo(loc2);
		}
		return distance / 1000;
	}

	private static int getTime(int lastResourcePoint, int currentResourcePoint,
			List<TripPoint> pointList) {
		int time = 0;
		for (int i = lastResourcePoint + 1; i < currentResourcePoint; i++) {
			time += pointList.get(i).time - pointList.get(i - 1).time;
		}
		return time;
	}

	private static float getAvgSpeed(int lastResourcePoint,
			int currentResourcePoint, List<TripPoint> pointList) {
		return getDistance(lastResourcePoint, currentResourcePoint, pointList)
				/ getTime(lastResourcePoint, currentResourcePoint, pointList);
	}

	private static InputStream getBitmapFromURL(String urlString)
			throws MalformedURLException, IOException {
		URL url = new URL(urlString);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoInput(true);
		connection.connect();
		InputStream input = connection.getInputStream();
		return input;
	}

	private static class MenuItem {
		String id;
		String text;

		public MenuItem(String id, String text) {
			this.id = id;
			this.text = text;
		}
	}

	public static class ExportTripToSD extends AsyncTask<Void, Void, Boolean> {
		private ProgressDialog dialog;
		private Context context;
		private int tripId;
		private String tripName;

		public ExportTripToSD(Context context, int tripId, String tripName) {
			this.context = context;
			this.tripId = tripId;
			this.tripName = tripName;
			dialog = new ProgressDialog(this.context);

		}

		protected void onPreExecute() {
			dialog.setMessage(context.getString(R.string.trip_list_exporting));
			dialog.setIndeterminate(true);
			dialog.setCancelable(false);
			dialog.show();
		}

		protected Boolean doInBackground(Void... source) {
			String toSave = "";
			ArrayList<String> sourceFiles = new ArrayList<String>();

			JSONArray tosavearray = new JSONArray();
			Cursor cursor = context.getContentResolver()
					.query(LocationProvider.CONTENT_URI_LOCATION,
							new String[] { LocationProvider.LOCATION_LONGITUDE,
									LocationProvider.LOCATION_LATITUDE,
									LocationProvider.LOCATION_TIME,
									LocationProvider.LOCATION_ID },
							LocationProvider.TRIP_ID + " ='" + tripId + "'",
							null, null);
			if (cursor != null)
				if (cursor.getCount() > 0) {
					JSONArray jarray = new JSONArray();
					while (cursor.moveToNext()) {
						try {
							JSONObject jobject = new JSONObject();
							jobject.put("location_long", cursor.getString(0));
							jobject.put("location_lat", cursor.getString(1));
							jobject.put("location_time", cursor.getString(2));
							jobject.put("id", cursor.getString(3));
							jarray.put(jobject);
						} catch (Exception e) {
							e.printStackTrace();
							return false;
						}
					}
					cursor.close();

					try {
						tosavearray.put(new JSONObject().put("locations",
								jarray));
					} catch (Exception e) {
						e.printStackTrace();
						return false;
					}
				}
			cursor = context.getContentResolver()
					.query(LocationProvider.CONTENT_URI_RESOURCES,
							new String[] {
									LocationProvider.RESOURCE_DESCRIPTION,
									LocationProvider.RESOURCE_FILENAME,
									LocationProvider.RESOURCE_TYPE,
									LocationProvider.LOCATION_ID },
							LocationProvider.TRIP_ID + " ='" + tripId + "'",
							null, null);
			if (cursor != null)
				if (cursor.getCount() > 0) {
					JSONArray jarray = new JSONArray();
					while (cursor.moveToNext()) {
						try {
							JSONObject jobject = new JSONObject();
							jobject.put("description", cursor.getString(0));
							jobject.put("filename", cursor.getString(1));
							if (!cursor.getString(1).equals("")) {
								String temp = "";
								switch (cursor.getInt(2)) {
								case 1:
									temp += "Voice/";
									break;
								case 2:
									temp += "Image/";
									break;
								case 3:
									temp += "Video/";
									break;
								default:
									break;
								}
								temp += cursor.getString(1);
								sourceFiles.add(temp);
							}
							jobject.put("type", cursor.getString(2));
							jobject.put("location_id", cursor.getString(3));
							jarray.put(jobject);
						} catch (Exception e) {
							e.printStackTrace();
							return false;
						}
					}
					cursor.close();

					try {
						tosavearray.put(new JSONObject().put("resources",
								jarray));
					} catch (Exception e) {
						e.printStackTrace();
						return false;
					}
				}
			cursor = context.getContentResolver()
					.query(LocationProvider.CONTENT_URI_TRIPS,
							new String[] { LocationProvider.TRIP_ID,
									LocationProvider.TRIP_LENGTH,
									LocationProvider.TRIP_TIME,
									LocationProvider.TRIP_NAME },
							LocationProvider.TRIP_ID + " ='" + tripId + "'",
							null, null);
			if (cursor != null)
				if (cursor.getCount() > 0) {
					JSONArray jarray = new JSONArray();
					while (cursor.moveToNext()) {
						try {
							JSONObject jobject = new JSONObject();
							jobject.put("trip_id", cursor.getString(0));
							jobject.put("length", cursor.getString(1));
							jobject.put("time", cursor.getString(2));
							jobject.put("name", cursor.getString(3));
							jarray.put(jobject);
						} catch (Exception e) {
							e.printStackTrace();
							return false;
						}
					}
					cursor.close();

					try {
						tosavearray.put(new JSONObject().put("trip", jarray));
					} catch (Exception e) {
						e.printStackTrace();
						return false;
					}
				}
			toSave = tosavearray.toString();
			try {
				File sdCard = Environment.getExternalStorageDirectory();
				File file = new File(sdCard.getAbsolutePath(), "location.bak");
				file.delete();
				FileOutputStream fOut;
				fOut = new FileOutputStream(file);
				OutputStreamWriter osw = new OutputStreamWriter(fOut);

				osw.write(toSave);
				osw.flush();
				osw.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}

			try {

				byte[] buffer = new byte[1024];
				String zipFileName = tripId + " " + tripName + ".tri";
				File sdCard = Environment.getExternalStorageDirectory();
				File file = new File(sdCard.getAbsolutePath() + "/"
						+ Constants.APP_FOLDER_NAME + "/" + tripId + " "
						+ tripName, zipFileName);
				file.delete();
				FileOutputStream fout = new FileOutputStream(file);
				ZipOutputStream zout = new ZipOutputStream(fout);

				for (int i = 0; i < sourceFiles.size(); i++) {
					File photo = new File(sdCard.getAbsolutePath(), "/"
							+ Constants.APP_FOLDER_NAME + "/" + tripId + " "
							+ tripName + "/" + sourceFiles.get(i));
					FileInputStream fin = new FileInputStream(photo);
					zout.putNextEntry(new ZipEntry(sourceFiles.get(i)));
					int length;

					while ((length = fin.read(buffer)) > 0) {
						zout.write(buffer, 0, length);
					}

					zout.closeEntry();
					fin.close();
				}
				File backupSettings = new File(sdCard.getAbsolutePath(),
						"location.bak");
				FileInputStream fin = new FileInputStream(backupSettings);
				zout.putNextEntry(new ZipEntry("location.bak"));
				int length;

				while ((length = fin.read(buffer)) > 0) {
					zout.write(buffer, 0, length);
				}

				zout.closeEntry();
				fin.close();
				File directory = new File(sdCard.getAbsolutePath(),
						"location.bak");
				directory.delete();
				zout.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}

			return true;
		}

		protected void onProgressUpdate(Void... progress) {
		}

		protected void onPostExecute(Boolean result) {
			if (dialog.isShowing())
				dialog.dismiss();
			if (result) {
				File sdCard = Environment.getExternalStorageDirectory();

				Toast.makeText(
						context,
						context.getString(R.string.exporiting_export_made)
								+ " " + sdCard.getAbsolutePath() + "/"
								+ Constants.APP_FOLDER_NAME +"/" + tripId
								+ " " + tripName + "/" + tripId + " "
								+ tripName + ".tri", Toast.LENGTH_SHORT).show();
			} else
				Toast.makeText(context,
						context.getString(R.string.exporiting_export_failed),
						Toast.LENGTH_SHORT).show();

		}
	}

}
